Build a Functions

Create a function birthday.matrix

 birthday.matrix <- function(maxn=30) 
  {
    ### Define a local function to compute the probability for a single n              ###
    birthday.prob = function(n = 23){
        1 - prod((365-(0:(n-1)))/365)
    }
    ### Create an n x 1 matrix, or a vector, from 1 to n                                            ###
    n = matrix(1:maxn, ncol=1)
    ### Compute the probabilities, p, for each of the values in n.                          ###
    ### The "1" which is the second argument indicates that the application     ###
    ### of the function birthday.prob is over the rows.                                           ###
    p = apply(n, 1, birthday.prob)
    ### Now return a data.frame that contains the (n,p) pairs.  This can             ###
    ### also be treated as a matrix.                                                                             ###
    return(data.frame(n,p))
  }

Run the Function

Run the function birthday.matrix using the default n=30.

birthday.matrix()
##     n           p
## 1   1 0.000000000
## 2   2 0.002739726
## 3   3 0.008204166
## 4   4 0.016355912
## 5   5 0.027135574
## 6   6 0.040462484
## 7   7 0.056235703
## 8   8 0.074335292
## 9   9 0.094623834
## 10 10 0.116948178
## 11 11 0.141141378
## 12 12 0.167024789
## 13 13 0.194410275
## 14 14 0.223102512
## 15 15 0.252901320
## 16 16 0.283604005
## 17 17 0.315007665
## 18 18 0.346911418
## 19 19 0.379118526
## 20 20 0.411438384
## 21 21 0.443688335
## 22 22 0.475695308
## 23 23 0.507297234
## 24 24 0.538344258
## 25 25 0.568699704
## 26 26 0.598240820
## 27 27 0.626859282
## 28 28 0.654461472
## 29 29 0.680968537
## 30 30 0.706316243

Plot the Probabilities

Now create a plot of the probabilities. Using type=”l” gives a line without points.

  plot(birthday.matrix(75),type="l")
  ### Add a horizontal line at p=0.5 using a dashed line type.
  abline(h=0.5,lty=2)
  ### Add a vertical line at n=23 using a dashed line type.
  abline(v=23, lty=2)
  ### Add a title.
  title("Probability of a Shared Birthday")